﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SIA.Panels.Input
{
    public delegate void InputValueAcquire(int value); 

    public partial class InputNumber : Form
    {
        public event InputValueAcquire inputValueAcquire;

        private int _numberDefault = 0;
        private int _number = 0;
        private Boolean _numberOk = true;
        private Label _label = null;

        public InputNumber()
        {
            InitializeComponent();
        }

        public InputNumber(int numberDefault)
            :this()
        {
            _numberDefault = numberDefault;
            _number = _numberDefault;
            textBox1.Text = numberDefault.ToString();
        }

        public InputNumber(Label label)
            : this()
        {
            _label = label;
            textBox1.Text = _label.Text;
            parseInt();
            this.Show();
        }


        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            parseInt();
        }

        private void parseInt()
        {
            if (int.TryParse(textBox1.Text, out  _number))
            {
                textBox1.ForeColor = Color.Black;
                _numberOk = true;
            }
            else
            {
                textBox1.ForeColor = Color.Red;
                _number = _numberDefault;
                _numberOk = false;
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Return  )&& _numberOk )
            {
                inputValueAcquire(_number);
                if (_label != null)
                {
                    _label.Invoke(new MethodInvoker(delegate { _label.Text = _number.ToString(); }));
                }
                this.Close();
            }
        }
    }
}
